package org.example.controller;

import cn.hutool.core.util.StrUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.example.common.ResponseMessage;
import org.example.entity.User;
import org.example.entity.dto.RegisterDto;
import org.example.entity.dto.UserDto;
import org.example.service.UserService;
import org.example.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Tag(name="user-controller",description = "user-controller")
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 新增用户
     * @param userDto
     */
    @Operation(summary = "新增用户")
    @PostMapping("/addUser")
    public ResponseMessage add(@RequestBody UserDto userDto){
        return userService.addUser(userDto);
    }

    @Operation(summary = "根据部门获取用户")
    @PostMapping("/get/{Dept}")
    public ResponseMessage<List<User>> getUserByDept(@PathVariable String Dept){
        List<User> userList = userService.getUserByDept(Dept);
        if (userList != null && !userList.isEmpty()){
            return ResponseMessage.success(userList);
        }
        return ResponseMessage.error();
    }

    @Operation(summary = "注册账号")
    @PostMapping("/register")
    public ResponseMessage register(@RequestBody RegisterDto registerDto){
        //注册验证，判断数据库是否有该用户
        if(StrUtil.isBlank(registerDto.getUserName()) || StrUtil.isBlank(registerDto.getPassWord())){
            return ResponseMessage.error("数据输入不合法");
        }
        RegisterDto users  = userService.register(registerDto);
        return ResponseMessage.success(users);
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public ResponseMessage login(@RequestBody User user){
        if(StrUtil.isBlank(user.getUserName()) || StrUtil.isBlank(user.getPassWord())){
            return ResponseMessage.error("数据输入不合法");
        }
            User users  = userService.login(user);
            return ResponseMessage.success(users.getToken());
    }

    @Operation(summary = "退出登录")
    @PostMapping("/logout")
    public ResponseMessage logout(HttpServletRequest request) {
        // 从请求中获取token
        String token = String.valueOf(TokenUtils.getCurrentUser());
        if (StrUtil.isBlank(token)){
            return ResponseMessage.error("用户未登录");
        }
        // 从请求中获取session
        HttpSession session = request.getSession();
        // 删除登录的用户信息
        session.removeAttribute(token);
        return ResponseMessage.success();
    }
}




